package com.xin.data.simbapesa.activity;

import android.content.Intent;
import android.text.Html;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;

import com.bumptech.glide.Glide;
import com.google.gson.JsonObject;
import com.xin.data.simbapesa.PathMaping;
import com.xin.data.simbapesa.R;
import com.xin.data.simbapesa.api.PU;
import com.xin.data.simbapesa.api.RxHttp;
import com.xin.data.simbapesa.api.U;
import com.xin.data.simbapesa.base.BaseActivity;
import com.xin.data.simbapesa.base.BaseParams;
import com.xin.data.simbapesa.databinding.SimbaFaceActivityBinding;
import com.xin.data.simbapesa.utils.AESCryptUtilJar;
import com.xin.data.simbapesa.utils.JsonParse;
import com.xin.data.simbapesa.utils.LogUtil;
import com.xin.data.simbapesa.utils.ResUtils;
import com.xin.data.simbapesa.utils.ViewUtils;

import java.util.HashMap;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;

public class SimbaFaceActivity extends BaseActivity<SimbaFaceActivityBinding> {


    String faceImgUrl;

    private long clickStartTime = 0;

    @Override
    protected SimbaFaceActivityBinding initViewBinding(LayoutInflater inflater) {
        return SimbaFaceActivityBinding.inflate(inflater);
    }

    @Override
    protected void initView() {

        binding.getRoot().setPadding(0, 0, 0, 0);
        setStatusBarHeight2(binding.tvRoot, ResUtils.d(R.dimen.dp_12), ResUtils.d(R.dimen.dp_12), ResUtils.d(R.dimen.dp_12));

        binding.tvHit1.setText(Html.fromHtml(ResUtils.s(R.string.ocr_hit1)));

        binding.tvBox.setSelected(true);

        binding.tvHitLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ViewUtils.viewScale(v);
                binding.tvBox.setSelected(!binding.tvBox.isSelected());
            }
        });

        binding.tvBk.setOnClickListener(v -> {
            ViewUtils.viewScale(v);
            PU.userBuriedPoint(PU.P157, "");
            finish();
        });
        binding.tvCs.setOnClickListener(v -> {
            ViewUtils.viewScale(v);
            PU.userBuriedPoint(PU.P156, "");
            startActivity(new Intent(getActivity(), SimbaCustomerServiceActivity.class));
        });

        binding.tvIcon.setOnClickListener(v -> {
            ViewUtils.viewScale(v);
            PU.userBuriedPoint(PU.P196, "1");
            clickStartTime = System.currentTimeMillis();
            Intent intent = new Intent(this, SimbaFaceCameraActivity.class);
            someActivityResultLauncher.launch(intent);
        });

        binding.tvBtn1.setOnClickListener(v -> {
            ViewUtils.viewScale(v);
            PU.userBuriedPoint(PU.P196, "3");
            clickStartTime = System.currentTimeMillis();
            Intent intent = new Intent(this, SimbaFaceCameraActivity.class);
            someActivityResultLauncher.launch(intent);
        });

        binding.tvBtn.setOnClickListener(v -> {
            ViewUtils.viewScale(v);
            PU.userBuriedPoint(PU.P196, "2");
            PU.userBuriedAllPoint(getActivity());
            ocrInfo();
        });

    }

    @Override
    protected void initData() {
        UP_TYPE1 = PU.P154;
        UP_TYPE2 = PU.P155;
    }

    void loadData() {
        if (getActivity() != null && !isFinishing()) {
            if (!TextUtils.isEmpty(faceImgUrl)) {
                LogUtil.e("me", "faceImgUrl->" + faceImgUrl);
                binding.tvIcon.setBorderWidth(ResUtils.d(R.dimen.dp_4));
                Glide.with(getActivity()).load(faceImgUrl).placeholder(R.color.placeholder_icon).into(binding.tvIcon);
                binding.tvBtn.setSelected(true);

                binding.tvReSet.setVisibility(View.VISIBLE);

                binding.tvBtnTxt.setText(ResUtils.s(R.string.face_btn2));

            } else {
                binding.tvIcon.setImageResource(R.mipmap.face_img);
                binding.tvIcon.setBorderWidth(0);
                binding.tvBtn.setSelected(false);

                binding.tvReSet.setVisibility(View.GONE);

                binding.tvBtnTxt.setText(ResUtils.s(R.string.face_btn1));

            }
        }
    }

    void ocrInfo() {

        if (TextUtils.isEmpty(faceImgUrl)) {
            clickStartTime = System.currentTimeMillis();
            Intent intent = new Intent(this, SimbaFaceCameraActivity.class);
            someActivityResultLauncher.launch(intent);
        } else {

            JsonObject json = BaseParams.getJsonObject(getActivity(), PathMaping.PathList[53]);
            json.addProperty("cardType", "FACE");
            json.addProperty("faceImgUrl", faceImgUrl);
            json.addProperty("cardImgUrl", "");
            json.addProperty("cardBackImgUrl", "");



            HashMap<String, String> heads = new HashMap<>();
            heads.put("product", U.URL_PRODUCT);
            if (!TextUtils.isEmpty(U.URL_COUNTRY)) {
                heads.put("country", U.URL_COUNTRY);
            }

            showLoading("");

            RxHttp.post(U.commonUrl, AESCryptUtilJar.encryptDefault(json.toString()), heads)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<>() {
                        @Override
                        public void onSubscribe(@io.reactivex.rxjava3.annotations.NonNull Disposable d) {

                        }

                        @Override
                        public void onNext(@io.reactivex.rxjava3.annotations.NonNull String s) {
                            if(binding!=null) {
                                hideLoading();
                                if (!TextUtils.isEmpty(s)) {
                                    String json1 = AESCryptUtilJar.decryptDefault(s);
                                    if (JsonParse.getCode(json1)) {
                                        String token = JsonParse.ocrInfoJson2Obj(json1);
                                        LogUtil.e("me", "ocrInfo json->" + token);
                                        if (!TextUtils.isEmpty(token)) {
                                            userProcess(() -> {
                                                if (binding.tvBox.isSelected()) {
                                                    Toast.makeText(getActivity(), getResources().getString(R.string.ocr_tips5), Toast.LENGTH_LONG).show();
                                                }
                                                boolean isCheckSteps = checkSteps();
                                                if (!isCheckSteps) {
                                                    startActivity(new Intent(getActivity(), SimbaApplyActivity.class));
                                                }
                                                finish();
                                            }, true);
                                        }
                                    } else {
                                        showToastDialog(R.mipmap.hit_icon, JsonParse.getMsg(getActivity(), json1));
                                    }
                                }
                            }
                        }

                        @Override
                        public void onError(@io.reactivex.rxjava3.annotations.NonNull Throwable e) {
                            if(binding!=null) {
                                hideLoading();
                                showToastDialog(R.mipmap.hit_icon, getResources().getString(R.string.start_net_failed));
                            }
                        }

                        @Override
                        public void onComplete() {

                        }
                    });
        }
    }

    final ActivityResultLauncher<Intent> someActivityResultLauncher = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(),
            result -> {
                LogUtil.e("me", "--onActivityResult--");
                if (result.getResultCode() == RESULT_OK) {
                    Intent data = result.getData();
                    if (data != null) {
                        String url = data.getStringExtra("url");
                        LogUtil.e("me", "onActivityResult url->" + url);
                        if (!TextUtils.isEmpty(url)) {
                            faceImgUrl = url;
                            loadData();
                            long clickEndTime = System.currentTimeMillis();
                            PU.userBuriedPoint(PU.P174, faceImgUrl + "$$" + (clickEndTime - clickStartTime));
                        }
                    }
                }
            }
    );


}
